#!/usr/bin/env bash

set -eux

export LD_LIBRARY_PATH="$SNAP/lib:$SNAP/usr/lib:$SNAP/lib/x86_64-linux-gnu:$SNAP/usr/lib/x86_64-linux-gnu"
export PATH="$SNAP/usr/sbin:$SNAP/usr/bin:$SNAP/sbin:$SNAP/bin:$PATH:/usr/bin:/usr/local/bin"

source $SNAP/actions/common/utils.sh

cp -r ${SNAP}/default-args ${SNAP_DATA}/args

# Create the certificates
mkdir ${SNAP_DATA}/certs
# Allow the ability to add external IPs to the csr, by moving the csr.conf.template to SNAP_DATA 
cp ${SNAP}/certs/csr.conf.template ${SNAP_DATA}/certs/csr.conf.template
openssl genrsa -out ${SNAP_DATA}/certs/serviceaccount.key 2048
openssl genrsa -out ${SNAP_DATA}/certs/ca.key 2048
openssl req -x509 -new -nodes -key ${SNAP_DATA}/certs/ca.key -subj "/CN=127.0.0.1" -days 10000 -out ${SNAP_DATA}/certs/ca.crt
openssl genrsa -out ${SNAP_DATA}/certs/server.key 2048
produce_server_cert
rm -rf .srl

# Create the basic tokens
mkdir ${SNAP_DATA}/credentials
admin_token=$(openssl rand -base64 32 | ${SNAP}/usr/bin/base64)
echo "${admin_token},admin,admin,\"system:masters\"" > ${SNAP_DATA}/credentials/basic_auth.csv
chmod 600 ${SNAP_DATA}/credentials/basic_auth.csv

# Create the client kubeconfig
cp ${SNAP}/client.config.template ${SNAP_DATA}/credentials/client.config
# This is not safe. Everyone with local access can see these credentials.
chmod 644 ${SNAP_DATA}/credentials/client.config
$SNAP/bin/sed -i 's/PASSWORD/'"${admin_token}"'/g' ${SNAP_DATA}/credentials/client.config
ca_data=$(cat ${SNAP_DATA}/certs/ca.crt | ${SNAP}/usr/bin/base64 -w 0)
$SNAP/bin/sed -i 's/CADATA/'"${ca_data}"'/g' ${SNAP_DATA}/credentials/client.config